﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    /// <summary>
    /// 萤石视频接口调用
    /// </summary>
    public class YingShiController : Controller
    {

        /// <summary>
        /// 判断视频是否在线（是否在分享）
        /// </summary>
        /// <returns></returns>
        public string CheckVideoStatus()
        {
            string jsonTxt = "";
            try
            {
                string xuliehao = Request["xuliehao"];//摄像头序列号
                string serverTime = GetServerTime();
                string accessTokenJson = GetAccessToken(serverTime);
                Result obj2 = JsonConvert.DeserializeObject<Result>(accessTokenJson);
                ResultData resultdata2 = JsonConvert.DeserializeObject<ResultData>(obj2.result.ToString());
                AccessToken accessTokenData = JsonConvert.DeserializeObject<AccessToken>(resultdata2.data.ToString());
                string accessToken = accessTokenData.accessToken;

                //判断摄像头是否在线
                string backTxt = GetCameraInfo(serverTime, xuliehao, accessToken);
                Result obj3 = JsonConvert.DeserializeObject<Result>(backTxt);
                ResultData resultdata3 = JsonConvert.DeserializeObject<ResultData>(obj3.result.ToString());
                if (resultdata3.data!=null)
                {
                    string dataTxt = resultdata3.data.ToString().TrimStart('{').TrimEnd('}');
                    List<CameraInfo> mm = JsonConvert.DeserializeObject<List<CameraInfo>>(dataTxt);
                    if (mm != null)
                    {
                        if (mm[0] != null)
                        {
                            jsonTxt = mm[0].status + "";
                        }
                    }
                }
                else
                {
                    jsonTxt = resultdata3.msg;
                }
                //string dataTxt = resultdata3.data.ToString().TrimStart('{').TrimEnd('}');
                //List<CameraInfo> mm = JsonConvert.DeserializeObject<List<CameraInfo>>(dataTxt);
                //0：不在线，1：在线
                //if (mm[0].status == 1)
                //{
                //    backTxt = "在线";
                //}
                //else if (mm[0].status == 0)
                //{
                //    backTxt = "不在线";
                //}                          
            }
            catch (Exception ex)
            {
                jsonTxt = "\"error500\"";
                string saveFolder = "Log\\Controller";
                string msg = "YingShi/CheckVideoStatus，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(\"" + jsonTxt + "\")";
            return back;
        }

        /// <summary>
        /// 获取萤石云平台系统时间
        /// </summary>
        /// <returns></returns>
        public string GetServerTime()
        {
            string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"];
            string urlTime = "https://open.ys7.com/api/time/get?id=1&appKey="+ appKey;
            string serverTimeJson = RequestWebAPI(urlTime, "");
            Result obj = JsonConvert.DeserializeObject<Result>(serverTimeJson);
            ResultData resultdata = JsonConvert.DeserializeObject<ResultData>(obj.result.ToString());
            YSTime ystime = JsonConvert.DeserializeObject<YSTime>(resultdata.data.ToString());
            string serverTime = ystime.serverTime;//服务器时间戳
            return serverTime;
        }

        /// <summary>
        /// 根据序列号获取摄像头信息
        /// </summary>
        /// <param name="serverTime"></param>
        /// <param name="cameraId">摄像头序列号</param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public string GetCameraInfo(string serverTime, string cameraId, string accessToken)
        {
            //app配置信息
            string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"];
            string secret = System.Configuration.ConfigurationManager.AppSettings["secret"];
            
            long utk = long.Parse(serverTime);//             
            //签名源计算字符串
            var jmTxt = "accessToken:" + accessToken + ",deviceSerial:" + cameraId + ",method:camera/getCameraInfo,time:" + utk + ",secret:"+ secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "camera/getCameraInfo",
                @params = new
                {
                    accessToken = accessToken, //访问校验码
                    deviceSerial = cameraId   //设备9位短序列号
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            string backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }

        /// <summary>
        /// 获取accessToken
        /// </summary>
        /// <param name="serverTime"></param>
        /// <returns></returns>
        public string GetAccessToken(string serverTime)
        {
            //app配置信息
            string appKey = System.Configuration.ConfigurationManager.AppSettings["appKey"];
            string secret = System.Configuration.ConfigurationManager.AppSettings["secret"];
            string phone = System.Configuration.ConfigurationManager.AppSettings["phone"];
            long utk = long.Parse(serverTime);//             
            //签名源计算字符串
            var jmTxt = "phone:"+ phone + ",method:token/getAccessToken,time:" + utk + ",secret:"+ secret;
            string sign = Jiami.GetMD5(jmTxt);
            var dataObj = new
            {
                id = "1",
                method = "token/getAccessToken",
                @params = new
                {
                    phone = phone
                },
                system = new
                {
                    key = appKey,
                    sign = sign,
                    time = utk,
                    ver = "1.0"
                }
            };
            string sendJson = JsonConvert.SerializeObject(dataObj);//发送的json数据
            string url = "https://open.ys7.com/api/method";//接口
            string backTxt = RequestWebAPI(url, sendJson);
            return backTxt;
        }

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">参数</param>
        /// <returns></returns>
        public string RequestWebAPI(string url, string sendData)
        {
            string backMsg = "";
            try
            {
                System.Net.HttpWebRequest httpRquest = System.Net.HttpWebRequest.CreateHttp(url);
                httpRquest.Method = "POST";
                //httpRquest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                System.IO.Stream requestStream = httpRquest.GetRequestStream();
                if (string.IsNullOrWhiteSpace(sendData) == false)
                {
                    byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(sendData);
                    requestStream.Write(dataArray, 0, dataArray.Length);
                }
                System.Net.WebResponse response = httpRquest.GetResponse();
                System.IO.Stream responseStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, System.Text.Encoding.UTF8);
                backMsg = reader.ReadToEnd();

                reader.Close();
                reader.Dispose();

                requestStream.Close();
                requestStream.Dispose();
                responseStream.Close();
                responseStream.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return backMsg;
        }

    }
}